﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace DotNet.Common
{
    public class UDPDataReceivedEventArgs : EventArgs
    {
        public UDPDataReceivedEventArgs(byte[] data, int length)
        {
            m_Data = (byte[])data.Clone();
            m_length = length;
        }

        byte[] m_Data;
        public byte[] Data
        {
            get { return m_Data; }
        }

        int m_length;
        public int Length
        {
            get { return m_length; }
        }
    }

    public class UDPCommunicateServer
    {
        #region 变量
        int _bufferSize;
        bool m_IsRunning;

        byte[] m_receiveData;
        int m_receiveLength;
        Socket m_UdpServer;
        Thread m_DataReceiveProcThread;
        AsynIDQueue m_idQueue;
        #endregion

        #region 事件定义
        public delegate void OnReceivedDataHandler(IAsynIDLock waiter, UDPDataReceivedEventArgs e);
        public event OnReceivedDataHandler OnRecivedData;
        #endregion

        ushort _port;
        public ushort Port
        {
            get { return _port; }
            set { _port = value; }
        }

        int _timeout;
        public int Timeout
        {
            get { return _timeout; }
            set { _timeout = value; }
        }

        #region 构造方法
        public UDPCommunicateServer() : this(8000, 1024) { }

        public UDPCommunicateServer(ushort port)
            : this(port, 1024)
        {

        }

        public UDPCommunicateServer(ushort port, int bufferSize)
        {
            m_IsRunning = false;

            _port = port;
            _bufferSize = bufferSize;
            m_receiveData = new byte[_bufferSize];
            m_idQueue = new AsynIDQueue();
            _timeout = 1000;

            m_DataReceiveProcThread = new Thread(new ThreadStart(DataReceiveProc));
        }

        ~UDPCommunicateServer()
        {
            Stop();
        }
        #endregion

        public bool Start()
        {
            if (m_IsRunning)
                return false;

            try
            {
                m_UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, (int)_port);
                m_UdpServer.ReceiveTimeout = _timeout;
                m_UdpServer.Bind(ipep);

                m_idQueue.Start();
                m_DataReceiveProcThread.Start();

                m_IsRunning = true;

                return true;
            }
            catch //(Exception ex)
            {
                return false;
            }
        }

        public bool Stop()
        {
            if (m_IsRunning)
            {
                try
                {
                    m_IsRunning = false;
                    m_UdpServer.Close();
                    m_idQueue.Stop();
                    m_DataReceiveProcThread.Abort();
                }
                catch //(Exception ex)
                {
                    return false;//Trace.WriteLine(ex.Message);
                }
            }

            return true;
        }

        AutoResetEvent _autoReceiveEvent = new AutoResetEvent(false);
        UDPDataReceivedEventArgs _udpData;
        bool _pickFlag = false;
        public bool Receive(out UDPDataReceivedEventArgs udpData)
        {
            udpData = null;
            if (!m_IsRunning)
            {
                return false;
            }

            _pickFlag = true;
            _autoReceiveEvent.Reset();
            if (!_autoReceiveEvent.WaitOne(_timeout))
            {
                return false;
            }

            udpData = _udpData;
            return true;
        }

        private void DataReceiveProc()
        {
            UDPDataReceivedEventArgs udpData;
            while (m_IsRunning)
            {
                try
                {
                    m_receiveLength = m_UdpServer.Receive(m_receiveData);

                    udpData = new UDPDataReceivedEventArgs(m_receiveData, m_receiveLength);
                    if (_pickFlag)
                    {
                        _pickFlag = false;
                        _udpData = udpData;
                        _autoReceiveEvent.Set();
                    }

                    if (OnRecivedData != null)
                    {
                        OnRecivedData.BeginInvoke(new AsynID(m_idQueue), udpData, null, null);
                    }
                }
                catch //(Exception ex)
                {
                    //if (ex is SocketException)
                    //    ExceptionTracker.WriteExceptionInformation(ex);
                }
            }
        }
    }
}
